<?php
// 加载通用文件
require_once __DIR__ . '/../common/autoload.php';

// 检查是否已安装
if (!file_exists(__DIR__ . '/../.installed')) {
    json_response(['success' => false, 'message' => '系统未安装'], 503);
}

// 检查是否为Ajax请求
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    json_response(['success' => false, 'message' => '非法请求'], 403);
}

// 加载WebSocket客户端
if (file_exists(__DIR__ . '/../App/WebSocketClient.php')) {
    require_once __DIR__ . '/../App/WebSocketClient.php';
} else if (file_exists(__DIR__ . '/../websocket/src/WebSocketClient.php')) {
    require_once __DIR__ . '/../websocket/src/WebSocketClient.php';
}

// 处理不同的操作
$action = isset($_GET['action']) ? $_GET['action'] : '';

// 如果是POST请求，从JSON请求体中获取数据
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $json_data = file_get_contents('php://input');
    $data = json_decode($json_data, true);
    if (isset($data['action'])) {
        $action = $data['action'];
    }
}

// 记录请求信息以便调试
error_log("订单API请求: 操作={$action}, 方法={$_SERVER['REQUEST_METHOD']}");

try {
    switch ($action) {
        case 'create':
            // 创建订单
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                json_response(['success' => false, 'message' => '请求方法不正确'], 405);
            }
            
            // POS终端创建订单需要登录
            check_login();
            createOrder($data);
            break;
        case 'get':
            // 获取订单详情
            getOrder();
            break;
        case 'get_active':
            // 获取活动订单（等待中、制作中）
            getActiveOrders();
            break;
        case 'update_status':
            // 更新订单状态
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                json_response(['success' => false, 'message' => '请求方法不正确'], 405);
            }
            
            // 更新订单状态需要登录
            check_login();
            updateOrderStatus($data);
            break;
        case 'cancel':
            // 取消订单
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                json_response(['success' => false, 'message' => '请求方法不正确'], 405);
            }
            
            // 取消订单需要登录
            check_login();
            cancelOrder($data);
            break;
        case 'update_item_status':
            // 更新订单项状态
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                json_response(['success' => false, 'message' => '请求方法不正确'], 405);
            }
            
            // 更新订单项状态需要登录
            check_login();
            updateOrderItemStatus($data);
            break;
        case 'complete_all_items':
            // 完成订单的所有菜品
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                json_response(['success' => false, 'message' => '请求方法不正确'], 405);
            }
            
            // 完成所有菜品需要登录
            check_login();
            completeAllOrderItems($data);
            break;
        default:
            json_response(['success' => false, 'message' => '未知操作'], 400);
            break;
    }
} catch (Exception $e) {
    json_response(['success' => false, 'message' => $e->getMessage()], 500);
}

/**
 * 创建订单
 * @param array $data 请求数据
 */
function createOrder($data) {
    // 验证参数
    if (!isset($data['payment_method'])) {
        json_response(['success' => false, 'message' => '缺少必要参数'], 400);
    }
    
    $payment_method = $data['payment_method'];
    $member_id = isset($data['member_id']) && !empty($data['member_id']) ? intval($data['member_id']) : null;
    $remark = $data['remark'] ?? '';
    
    // 获取当前用户（收银员）
    $cashier = current_user();
    if (!$cashier) {
        json_response(['success' => false, 'message' => '未登录'], 401);
    }
    
    // 获取购物车
    $session_id = session_id();
    
    $cart_items = Database::fetchAll("SELECT c.*, p.name as product_name, p.price 
                                    FROM cart_items c 
                                    JOIN products p ON c.product_id = p.id 
                                    WHERE c.session_id = ? 
                                    ORDER BY c.created_at", [$session_id]);
    
    if (empty($cart_items)) {
        json_response(['success' => false, 'message' => '购物车为空，无法创建订单'], 400);
    }
    
    // 检查会员
    if ($member_id !== null) {
        $member = Database::fetch("SELECT * FROM users WHERE id = ? AND role = 'member'", [$member_id]);
        if (!$member) {
            json_response(['success' => false, 'message' => '会员不存在'], 404);
        }
        
        // 如果是余额支付，检查余额是否足够
        if ($payment_method === 'balance') {
            // 计算总价
            $total_price = 0;
            foreach ($cart_items as $item) {
                $total_price += $item['price'] * $item['quantity'];
            }
            
            if ($member['balance'] < $total_price) {
                json_response(['success' => false, 'message' => '会员余额不足'], 400);
            }
        }
    } else if ($payment_method === 'balance') {
        json_response(['success' => false, 'message' => '余额支付必须选择会员'], 400);
    }
    
    // 计算订单金额
    $total_price = 0;
    foreach ($cart_items as $item) {
        $total_price += $item['price'] * $item['quantity'];
    }
    
    // 获取最新的餐号
    $today = date('Y-m-d');
    $today_start = $today . ' 00:00:00';
    $today_end = $today . ' 23:59:59';
    
    $last_order = Database::fetch("SELECT MAX(queue_number) as last_num FROM orders WHERE created_at BETWEEN ? AND ?", [$today_start, $today_end]);
    $queue_number = ($last_order && $last_order['last_num']) ? $last_order['last_num'] + 1 : 1;
    
    // 开始事务
    $pdo = Database::getInstance();
    $pdo->beginTransaction();
    
    try {
        // 创建订单
        $order_data = [
            'order_no' => generate_order_number(),
            'user_id' => $member_id,
            'queue_number' => $queue_number,
            'total_price' => $total_price,
            'discount_price' => 0, // 暂不考虑优惠
            'actual_price' => $total_price,
            'payment_method' => $payment_method,
            'status' => 'paid', // 直接设为已支付
            'cashier_id' => $cashier['id'],
            'remark' => $remark
        ];
        
        $order_id = Database::insert('orders', $order_data);
        
        if (!$order_id) {
            throw new Exception('创建订单失败');
        }
        
        // 创建订单明细
        foreach ($cart_items as $item) {
            $item_data = [
                'order_id' => $order_id,
                'product_id' => $item['product_id'],
                'product_name' => $item['product_name'],
                'price' => $item['price'],
                'quantity' => $item['quantity'],
                'subtotal' => $item['price'] * $item['quantity'],
                'status' => 'pending'
            ];
            
            $item_id = Database::insert('order_items', $item_data);
            
            if (!$item_id) {
                throw new Exception('创建订单明细失败');
            }
        }
        
        // 如果是余额支付，扣除会员余额
        if ($payment_method === 'balance' && $member_id) {
            $new_balance = $member['balance'] - $total_price;
            Database::update('users', ['balance' => $new_balance], 'id = ?', [$member_id]);
        }
        
        // 为会员增加积分（基于消费金额）
        if ($member_id) {
            $points_to_add = floor($total_price); // 1元=1积分
            $member = Database::fetch("SELECT * FROM users WHERE id = ?", [$member_id]);
            $new_points = $member['points'] + $points_to_add;
            Database::update('users', ['points' => $new_points], 'id = ?', [$member_id]);
        }
        
        // 清空购物车
        Database::delete('cart_items', 'session_id = ?', [$session_id]);
        
        // 提交事务
        $pdo->commit();
        
        // 获取创建的订单
        $order = Database::fetch("SELECT * FROM orders WHERE id = ?", [$order_id]);
        
        // 发送WebSocket消息
        try {
            $client = new App\WebSocketClient();
            $result = $client->sendNewOrder($order);
            
            if (!$result) {
                error_log('发送WebSocket新订单消息失败');
            } else {
                error_log('成功发送新订单WebSocket消息，实时通知排队显示屏');
            }
        } catch (\Exception $e) {
            // 记录错误但不影响订单创建
            error_log('WebSocket通信错误: ' . $e->getMessage());
        }
        
        json_response([
            'success' => true, 
            'message' => '订单创建成功',
            'order' => $order,
            'order_id' => $order_id
        ]);
        
    } catch (Exception $e) {
        // 回滚事务
        $pdo->rollBack();
        json_response(['success' => false, 'message' => $e->getMessage()], 500);
    }
}

/**
 * 获取订单详情
 */
function getOrder() {
    $id = intval($_GET['id'] ?? 0);
    
    if ($id <= 0) {
        json_response(['success' => false, 'message' => '无效的订单ID'], 400);
    }
    
    try {
        // 检查用户登录状态
        $current_user = current_user();
        if (!$current_user) {
            json_response(['success' => false, 'message' => '请先登录'], 401);
        }
        
        // 获取订单基本信息
        $order = Database::fetch("SELECT o.*, u.name as member_name, u.phone as member_phone, c.name as cashier_name 
                                FROM orders o 
                                LEFT JOIN users u ON o.user_id = u.id 
                                LEFT JOIN users c ON o.cashier_id = c.id 
                                WHERE o.id = ?", [$id]);
        
        if (!$order) {
            json_response(['success' => false, 'message' => '订单不存在'], 404);
        }
        
        // 会员只能查看自己的订单，管理员和收银员可以查看所有订单
        if ($current_user['role'] === 'member' && $order['user_id'] != $current_user['id']) {
            json_response(['success' => false, 'message' => '您无权查看此订单'], 403);
        }
        
        // 获取订单明细
        $order_items = Database::fetchAll("SELECT * FROM order_items WHERE order_id = ? ORDER BY id", [$id]);
        
        // 确保所有必要字段存在，即使优惠券功能已被删除
        if (!isset($order['discount_price'])) {
            $order['discount_price'] = 0;
        }
        
        // 处理订单状态
        $valid_statuses = ['pending', 'paid', 'cooking', 'completed', 'cancelled', 'taken'];
        if (!in_array($order['status'], $valid_statuses)) {
            // 兼容可能的自定义状态
            $order['display_status'] = $order['status'];
        } else {
            $order['display_status'] = $order['status'];
        }
        
        json_response([
            'success' => true, 
            'order' => $order,
            'items' => $order_items
        ]);
    } catch (Exception $e) {
        error_log('获取订单详情失败: ' . $e->getMessage());
        json_response(['success' => false, 'message' => '获取订单详情失败，请稍后重试'], 500);
    }
}

/**
 * 获取活动订单
 */
function getActiveOrders() {
    // 获取活动订单列表
    $orders = Database::fetchAll("SELECT o.*, u.name as member_name 
                                FROM orders o 
                                LEFT JOIN users u ON o.user_id = u.id 
                                WHERE o.status IN ('paid', 'cooking') 
                                ORDER BY o.created_at DESC");
    
    json_response([
        'success' => true, 
        'orders' => $orders
    ]);
}

/**
 * 更新订单状态
 * @param array $data 请求数据
 */
function updateOrderStatus($data) {
    // 验证参数
    if (!isset($data['order_id']) || !isset($data['status'])) {
        json_response(['success' => false, 'message' => '缺少必要参数'], 400);
    }
    
    $order_id = intval($data['order_id']);
    $status = $data['status'];
    
    // 验证状态
    $valid_statuses = ['paid', 'cooking', 'completed', 'cancelled'];
    if (!in_array($status, $valid_statuses)) {
        json_response(['success' => false, 'message' => '无效的订单状态'], 400);
    }
    
    // 获取订单
    $order = Database::fetch("SELECT * FROM orders WHERE id = ?", [$order_id]);
    if (!$order) {
        json_response(['success' => false, 'message' => '订单不存在'], 404);
    }
    
    // 不能更新已取消的订单
    if ($order['status'] === 'cancelled') {
        json_response(['success' => false, 'message' => '已取消的订单不能更新状态'], 400);
    }
    
    // 开始事务
    $pdo = Database::getInstance();
    $pdo->beginTransaction();
    
    try {
        // 更新订单状态
        Database::update('orders', ['status' => $status], 'id = ?', [$order_id]);
        
        // 如果订单状态更新为完成，则更新所有订单项为完成
        if ($status === 'completed') {
            Database::update('order_items', ['status' => 'completed'], 'order_id = ? AND status != "completed"', [$order_id]);
        }
        
        // 如果订单状态更新为取消，则退款
        if ($status === 'cancelled' && $order['status'] !== 'cancelled') {
            if ($order['payment_method'] === 'balance' && $order['user_id']) {
                // 会员余额退款
                $member = Database::fetch("SELECT * FROM users WHERE id = ?", [$order['user_id']]);
                if ($member) {
                    $new_balance = $member['balance'] + $order['actual_price'];
                    Database::update('users', ['balance' => $new_balance], 'id = ?', [$order['user_id']]);
                    
                    // 扣除对应的积分
                    $points_to_deduct = floor($order['actual_price']);
                    $new_points = max(0, $member['points'] - $points_to_deduct);
                    Database::update('users', ['points' => $new_points], 'id = ?', [$order['user_id']]);
                }
            }
        }
        
        // 提交事务
        $pdo->commit();
        
        // 获取更新后的订单
        $order = Database::fetch("SELECT * FROM orders WHERE id = ?", [$order_id]);
        
        // 获取更新后的订单项
        $order_items = Database::fetchAll("SELECT * FROM order_items WHERE order_id = ?", [$order_id]);
        
        // 发送WebSocket消息
        try {
            $client = new App\WebSocketClient();
            
            // 添加订单项到订单信息
            $order['items'] = $order_items;
            
            // 对于已完成或已取餐的订单，使用特殊处理确保排队显示屏实时更新
            if ($order['status'] === 'completed' || $order['status'] === 'taken') {
                $result = $client->sendOrderStatusUpdate($order);
                error_log('发送订单状态变更(' . $order['status'] . ')WebSocket消息，实时更新排队显示屏');
            } else {
                $result = $client->sendOrderStatusUpdate($order);
            }
            
            if (!$result) {
                error_log('发送WebSocket状态更新消息失败');
            }
        } catch (\Exception $e) {
            // 记录错误但不影响订单状态更新
            error_log('WebSocket通信错误: ' . $e->getMessage());
        }
        
        json_response([
            'success' => true, 
            'message' => '订单状态已更新',
            'order' => $order
        ]);
        
    } catch (Exception $e) {
        // 回滚事务
        $pdo->rollBack();
        json_response(['success' => false, 'message' => $e->getMessage()], 500);
    }
}

/**
 * 取消订单
 * @param array $data 请求数据
 */
function cancelOrder($data) {
    // 验证参数
    if (!isset($data['order_id'])) {
        json_response(['success' => false, 'message' => '缺少必要参数'], 400);
    }
    
    $order_id = intval($data['order_id']);
    
    // 获取订单
    $order = Database::fetch("SELECT * FROM orders WHERE id = ?", [$order_id]);
    if (!$order) {
        json_response(['success' => false, 'message' => '订单不存在'], 404);
    }
    
    // 不能取消已取消的订单
    if ($order['status'] === 'cancelled') {
        json_response(['success' => false, 'message' => '订单已经取消'], 400);
    }
    
    // 不能取消已完成的订单
    if ($order['status'] === 'completed') {
        json_response(['success' => false, 'message' => '已完成的订单不能取消'], 400);
    }
    
    // 调用更新订单状态
    $cancel_data = [
        'order_id' => $order_id,
        'status' => 'cancelled'
    ];
    
    updateOrderStatus($cancel_data);
}

/**
 * 更新订单项状态
 * @param array $data 请求数据
 */
function updateOrderItemStatus($data) {
    if (!isset($data['order_item_id']) || !isset($data['status'])) {
        json_response(['success' => false, 'message' => '缺少必要参数'], 400);
    }
    
    $item_id = intval($data['order_item_id']);
    $status = $data['status'];
    
    if (!in_array($status, ['pending', 'cooking', 'completed'])) {
        json_response(['success' => false, 'message' => '无效的状态值'], 400);
    }
    
    // 记录请求信息
    error_log("接收到订单项状态更新请求: 项目ID=$item_id, 状态=$status");
    
    // 获取订单项信息
    $item = Database::fetch("SELECT i.*, o.status as order_status FROM order_items i 
                           JOIN orders o ON i.order_id = o.id 
                           WHERE i.id = ?", [$item_id]);
    
    if (!$item) {
        json_response(['success' => false, 'message' => '订单项不存在'], 404);
    }
    
    error_log("找到订单项: " . json_encode($item));
    
    // 开始事务
    $pdo = Database::getInstance();
    $pdo->beginTransaction();
    
    try {
        // 更新订单项状态
        Database::update('order_items', ['status' => $status], 'id = ?', [$item_id]);
        
        // 获取订单所有订单项
        $items = Database::fetchAll("SELECT * FROM order_items WHERE order_id = ?", [$item['order_id']]);
        
        // 检查所有订单项是否都已完成
        $all_completed = true;
        foreach ($items as $i) {
            if ($i['status'] !== 'completed') {
                $all_completed = false;
                break;
            }
        }
        
        // 如果所有订单项都已完成，更新订单状态为已完成
        if ($all_completed && $item['order_status'] !== 'completed') {
            Database::update('orders', ['status' => 'completed'], 'id = ?', [$item['order_id']]);
        }
        // 如果有任何订单项正在制作中，且订单状态是已支付，更新订单状态为制作中
        else if ($status === 'cooking' && $item['order_status'] === 'paid') {
            Database::update('orders', ['status' => 'cooking'], 'id = ?', [$item['order_id']]);
        }
        
        // 提交事务
        $pdo->commit();
        
        // 获取更新后的订单项
        $order_item = Database::fetch("SELECT * FROM order_items WHERE id = ?", [$item_id]);
        
        // 获取更新后的订单
        $order = Database::fetch("SELECT * FROM orders WHERE id = ?", [$item['order_id']]);
        
        // 获取所有更新后的订单项
        $updated_items = Database::fetchAll("SELECT * FROM order_items WHERE order_id = ?", [$item['order_id']]);
        
        error_log("更新后的订单项状态: " . $order_item['status']);
        error_log("更新后的订单状态: " . $order['status']);
        
        // 发送WebSocket消息
        try {
            // 检查WebSocketClient类是否存在
            if (!class_exists('App\\WebSocketClient')) {
                error_log("错误: WebSocketClient类不存在，无法发送WebSocket消息");
                throw new \Exception("WebSocketClient类不存在");
            }
            
            $client = new App\WebSocketClient();
            
            // 1. 发送订单状态更新消息
            // 添加订单项到订单对象
            $order['items'] = $updated_items;
            $result = $client->sendOrderStatusUpdate($order);
            
            if (!$result) {
                error_log('发送WebSocket订单状态更新消息失败');
            } else {
                error_log('成功发送订单状态WebSocket消息: 订单ID=' . $order['id']);
            }
            
            // 2. 发送订单项状态更新消息
            $result2 = $client->sendOrderItemStatusUpdate($order_item, $item['order_id']);
            
            if (!$result2) {
                error_log('发送WebSocket订单项状态更新消息失败');
            } else {
                error_log('成功发送订单项状态WebSocket消息: 项目ID=' . $order_item['id']);
            }
        } catch (\Exception $e) {
            // 记录错误但不影响状态更新
            error_log('WebSocket通信错误: ' . $e->getMessage());
        }
        
        json_response([
            'success' => true, 
            'message' => '订单项状态已更新',
            'item' => $order_item,
            'order' => $order,
            'all_items' => $updated_items
        ]);
        
    } catch (Exception $e) {
        // 回滚事务
        $pdo->rollBack();
        error_log('更新订单项状态时出错: ' . $e->getMessage());
        json_response(['success' => false, 'message' => $e->getMessage()], 500);
    }
}

/**
 * 完成订单的所有菜品
 * @param array $data 请求数据
 */
function completeAllOrderItems($data) {
    // 验证参数
    if (!isset($data['order_id']) || empty($data['order_id'])) {
        json_response(['success' => false, 'message' => '缺少订单ID'], 400);
    }
    
    $order_id = intval($data['order_id']);
    
    // 检查订单是否存在
    $order = Database::fetch("SELECT * FROM orders WHERE id = ?", [$order_id]);
    if (!$order) {
        json_response(['success' => false, 'message' => '订单不存在'], 404);
    }
    
    // 检查订单状态
    if ($order['status'] !== 'cooking') {
        json_response(['success' => false, 'message' => '只有制作中的订单可以执行此操作'], 400);
    }
    
    // 开始事务
    $pdo = Database::getInstance();
    $pdo->beginTransaction();
    
    try {
        // 更新所有订单项为已完成
        $result = Database::query("UPDATE order_items SET status = 'completed' WHERE order_id = ?", [$order_id]);
        
        if ($result === false) {
            throw new Exception('更新订单项状态失败');
        }
        
        // 更新订单状态为已完成
        Database::update('orders', ['status' => 'completed'], 'id = ?', [$order_id]);
        
        // 提交事务
        $pdo->commit();
        
        // 获取更新后的订单
        $order = Database::fetch("SELECT * FROM orders WHERE id = ?", [$order_id]);
        
        // 获取更新后的订单项
        $order_items = Database::fetchAll("SELECT * FROM order_items WHERE order_id = ?", [$order_id]);
        
        // 发送WebSocket消息
        try {
            $client = new App\WebSocketClient();
            
            // 添加订单项到订单信息
            $order['items'] = $order_items;
            
            // 发送订单状态更新消息
            $result = $client->sendOrderStatusUpdate($order);
            
            if (!$result) {
                error_log('发送WebSocket状态更新消息失败');
            }
            
            // 为每个订单项发送状态更新消息
            foreach ($order_items as $item) {
                $result = $client->sendOrderItemStatusUpdate($item, $order_id);
                if (!$result) {
                    error_log('发送WebSocket订单项状态更新消息失败: 项目ID=' . $item['id']);
                }
            }
        } catch (\Exception $e) {
            // 记录错误但不影响订单状态更新
            error_log('WebSocket通信错误: ' . $e->getMessage());
        }
        
        // 确保返回有效的JSON响应
        json_response([
            'success' => true, 
            'message' => '所有菜品已标记为完成',
            'order' => $order,
            'order_items' => $order_items
        ]);
    } catch (Exception $e) {
        // 回滚事务
        $pdo->rollBack();
        error_log('完成所有菜品失败: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
        json_response(['success' => false, 'message' => $e->getMessage()], 500);
    }
} 